# -*- coding: utf-8 -*-
#--------------------------------------------------------------------------
# Copyright (c) 2009 Barry Schwartz
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

#--------------------------------------------------------------------------

import os
import re
import traceback
from . import (file_type, kpathsea, temp_dir, fontforge, tfm, libff)
#from kt import file_type, kpathsea, temp_dir, fontforge, tfm, libff

#--------------------------------------------------------------------------

def open_ff(file_name, kind = None):
    if kind == 'tfm':
        f = open_given_tex_metrics(file_name, kind)
    else:
        f = open_given_font_file(file_name, kind)
    return f

def open_given_tex_metrics(file_name, kind):
    tfm_name = os.path.splitext(os.path.basename(file_name))[0]
    (enc_name, font_name) = tfm.get_encoding_and_font_name(tfm_name)
    font_file = kpathsea.find_resource(font_name, format = kpathsea.kpse_type1_format)
    f = fontforge.open(font_file)
    if enc_name != '':
        enc_file = kpathsea.find_resource(enc_name, format = kpathsea.kpse_enc_format)
        (encoding_name, glyph_names_) = tfm.read_encoding_file(enc_file)
        fontforge.loadEncodingFile(enc_file)
        f.encoding = encoding_name
    f.mergeFeature(file_name)
    make_notdef(f)
    libff.swap_notdef(f)
    return f

def open_given_font_file(file_name, kind):
    f = fontforge.open(file_name)
    if kind == 'type1' and f.gpos_lookups == () and f.gsub_lookups == ():
        load_type1_metrics(f, file_name)
    if f.os2_version <= 1:
        f.os2_version = 2
    make_notdef(f)
    libff.swap_notdef(f)
    return f

def load_type1_metrics(f, file_name):
    if file_name[-4:].lower() in ('.pfb', '.pfa'):
        resource_name = os.path.basename(file_name[:-4])
    else:
        resource_name = os.path.basename(file_name)
    try:
        metrics_file = kpathsea.find_resource(resource_name, format = kpathsea.kpse_afm_format)
        f.mergeFeature(metrics_file)
        return
    except IOError:
        pass

def make_notdef(f):
    if '.notdef' not in f:
        f.createChar(-1, '.notdef')
        draw_notdef(f)
    elif not f['.notdef'].isWorthOutputting():
        draw_notdef(f)

def draw_notdef(f):
    width = f.em / 2
    left_space = f.em / 20
    width_used = width - 2 * left_space
    height = f.ascent
    top_space = f.ascent / 10
    height_used = height - top_space
    thickness = f.em / 20
    pen = f['.notdef'].glyphPen()
    pen.moveTo(left_space, 0)
    pen.lineTo(left_space, height_used)
    pen.lineTo(left_space + width_used, height_used)
    pen.lineTo(left_space + width_used, 0)
    pen.closePath()
    pen.moveTo(left_space + thickness, thickness)
    pen.lineTo(left_space + width_used - thickness, thickness)
    pen.lineTo(left_space + width_used - thickness, height_used - thickness)
    pen.lineTo(left_space + thickness, height_used - thickness)
    pen.closePath()
    pen = None
    f['.notdef'].width = width

def find_font(resource_name):
    # First try known formats in order of preference.
    for format in (kpathsea.kpse_opentype_format,
                   kpathsea.kpse_type1_format,
                   kpathsea.kpse_truetype_format,
                   kpathsea.kpse_tfm_format):
        try:
            return kpathsea.find_resource(resource_name, format = format)
        except IOError:
            pass
    return kpathsea.find_resource(resource_name)

# FIX: Make this keep track of and reuse opened fonts, so that they
# won't be opened many times.
def open_as_fontforge_font(resource_name):
    file_name = find_font(resource_name)
    kind = file_type.file_type(file_name)
    f = open_ff(file_name, kind = kind)
    (base_name, ignored_) = os.path.splitext(os.path.basename(resource_name))
    return (f, file_name, base_name)

#--------------------------------------------------------------------------
